<template>
	<div class="quanXian center align-start fWrap">
		<!-- <div class="right bfff">
			<div class="title">
				<div class="ctheme f14">权限角色分配</div>
			</div>
		</div> -->
		<div class="left flex">
			<div class="bfff left-bottom">
				<!-- <div class="labelTag">
					<el-tag>权限角色分配</el-tag>
				</div> -->
				<div class="title">权限角色分配</div>
				<div class="center flex-start fWrap table-head">
					<el-button
						class="primary"
						type="primary"
						@click="add"
						v-auth="['system:sysRole:save', 'system:sysRole:menuAuthList', 'system:sysRole:saveToAuth']"
						>+新增</el-button
					>
					<el-button
						class="danger"
						type="danger"
						plain
						@click="delTableList()"
						v-auth="['system:sysRole:deleteBatch']"
						>批量删除</el-button
					>
				</div>
				<div class="center table-head2">
					<div class="f16 choice-num flex ctheme">已选：{{ selectList.length }}</div>
				</div>
				<div class="table-scrol">
					<div class="table">
						<el-table @select="selectClick" @select-all="selectAll" :data="tableData" style="width: 100%">
							<el-table-column align="center" type="selection" min-width="60" />
							<el-table-column
								align="center"
								prop="name"
								label="角色名称"
								show-overflow-tooltip
								min-width="100"
							/>
							<el-table-column
								align="center"
								prop="remark"
								label="描述"
								show-overflow-tooltip
								min-width="200"
							/>
							<el-table-column align="center" label="操作" min-width="200">
								<template #default="{ row }">
									<div class="table-color">
										<el-button
											:icon="Remove"
											v-auth="['system:sysRole:dataAuth']"
											@click="authority(row)"
											title="数据权限"
										></el-button>
										<el-button
											:icon="EditPen"
											v-auth="[
												'system:sysRole:edit',
												'system:sysRole:menuAuthList',
												'system:sysRole:menuAuthInfoToRole',
												'system:sysRole:editToAuth',
											]"
											@click="editTable(row)"
											:disabled="row.name == '超级管理员'"
											title="编辑"
										></el-button>
										<el-button
											:icon="Delete"
											v-auth="['system:sysRole:delete']"
											@click="delTableList(row)"
											:disabled="row.name == '超级管理员'"
											title="删除"
										></el-button>
									</div>
								</template>
							</el-table-column>
							<template #empty>
								<el-empty description="暂无数据" />
							</template>
						</el-table>
						<div style="display: flex; justify-content: center; margin-top: 20px">
							<v-pagination
								:total="total"
								v-model:size="pageSize"
								v-model:page="current"
								@pagination="created"
								@paginations="created"
							></v-pagination>
						</div>
					</div>
				</div>
			</div>
		</div>
		<!-- 新增权限分配 -->
		<el-dialog
			class="cheng-dialog"
			v-model="visible"
			:show-close="false"
			:close-on-click-modal="false"
			destroy-on-close
			width="800px"
		>
			<template #header="{ close, titleId, titleClass }">
				<div class="dialog-header center btheme cfff">
					<img src="@/assets/image/houTai/quan.png" alt="" />
					<div class="flex f16 fbold">{{ title }}</div>
					<el-icon class="pointer" size="20" color="#fff" @click="quXiao">
						<Close />
					</el-icon>
				</div>
			</template>
			<div class="dialog-content">
				<el-form
					ref="ruleFormRef"
					:model="ruleForm"
					:rules="rules"
					class="demo-ruleForm"
					:size="formSize"
					status-icon
				>
					<el-form-item label="角色名称" prop="name">
						<el-input
							class="name"
							v-model="ruleForm.name"
							placeholder="请输入角色名称"
							maxlength="20"
							show-word-limit
						/>
					</el-form-item>
					<el-form-item label="权限分配" prop="limits">
						<!-- <el-collapse accordion class="w100">
							<el-collapse-item :name="index" v-for="(item, index) in limitsList" :key="index">
								<template #title>
									<div class="center f16 c666 w100 mr10">
										<div class="flex">{{ item.name }}</div>
									</div>
								</template>
								<div class="checkbox-item" v-for="(it, ind) in item.children" :key="it.id">
									<el-checkbox
										:indeterminate="isIndeterminate[it.id]"
										@change="handleCheckAllChange(it.id, it.children)"
										v-model="checkbox[it.id]"
									>
										<template #default>
											<div>{{ it.name }}</div>
										</template>
									</el-checkbox>
									<el-checkbox-group v-model="ruleForm.limits">
										<el-checkbox
											:label="i.id"
											v-for="i in it.children"
											:key="i.id"
											@change="handleCheckedCitiesChange(it.id, it.children)"
										>
											<template #default>
												<div>
													{{ i.name }}
												</div>
												<el-checkbox :label="ite.id" v-for="ite in i.children" :key="ite.id">
													<template #default>
														<div>
															{{ ite.name }}
														</div>
													</template>
												</el-checkbox>
											</template>
										</el-checkbox>
									</el-checkbox-group>
								</div>
							</el-collapse-item>
						</el-collapse> -->
						<div class="el-tree">
							<el-tree
								ref="limitsTree"
								:data="limitsList"
								show-checkbox
								node-key="id"
								:props="{ value: 'id', label: 'name', children: 'children' }"
								@check="handleCheckChange"
							/>
						</div>
					</el-form-item>
					<el-form-item label="角色描述" prop="remark">
						<el-input
							type="textarea"
							class="name"
							v-model="ruleForm.remark"
							placeholder="请输入角色描述"
							maxlength="100"
							show-word-limit
						/>
						<div class="center space-between c60 w100">
							<span>创建者 {{ userInfo }}</span>
							<span>创建时间 {{ times }}</span>
						</div>
					</el-form-item>
				</el-form>
			</div>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="quXiao">取消</el-button>
					<el-button type="primary" @click="submitForm(ruleFormRef)"> 确定 </el-button>
				</div>
			</template>
		</el-dialog>
		<el-dialog
			class="dialog"
			v-model="authorityVis"
			:show-close="false"
			:close-on-click-modal="false"
			destroy-on-close
		>
			<template #header="{ close, titleId, titleClass }">
				<div class="dialog-header center btheme cfff">
					<img src="@/assets/image/zhuTi/xin.png" alt="" />
					<div class="flex f16 fbold">权限调整</div>
					<el-icon class="pointer" size="20" color="#fff" @click="closes">
						<Close />
					</el-icon>
				</div>
			</template>
			<div class="dialog-contents">
				<el-tree
					show-checkbox
					default-expand-all
					ref="tree"
					:data="data"
					node-key="id"
					:props="{ value: 'id', label: 'name', children: 'children' }"
					@check="checkChange"
				/>
			</div>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="closes">取消</el-button>
					<el-button type="primary" @click="onYes"> 确定 </el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
import { Search, RefreshRight, EditPen, Delete, Remove } from "@element-plus/icons-vue"
import { ElMessage, ElMessageBox } from "element-plus"
import { nextTick } from "vue"
const { proxy } = getCurrentInstance()
const route = useRoute()
const router = useRouter()
const dataTime = new Date().getTime()
const defaultTree = ref([])
const tree = ref()
const limitsTree = ref()
const selectList = ref([])
const pageSize = ref(10)
const data = ref([])
const fabu = ref(false)
const timeType = ref(false)
// 新增权限分配
const visible = ref(false)
const authorityVis = ref(false)

const setShowMore = () => {
	visible.value = !visible.value
}
const ruleForm = reactive({
	name: "",
	limits: [],
	remark: "",
})
const rules = reactive({
	name: [
		{
			required: true,
			message: "请输入角色昵称",
			trigger: "blur",
		},
	],
	limits: [
		{
			required: true,
			message: "请分配权限",
			trigger: "blur",
		},
	],
})
const ruleFormRef = ref()
const authorityList = ref([])
const authorityStr = ref("")
//一级菜单列表
const checkbox = ref({})
const total = ref(0)
const current = ref(1)
const checkList = ref([])
const limitsList = ref([])
// const isIndeterminate = ref([])

//全局搜索
const onSearchText = ref("")
const submitForm = async formEl => {
	if (fabu.value) {
		return
	} else {
		fabu.value = true
		if (!formEl) return
		await formEl.validate(async (valid, fields) => {
			if (valid) {
				let obj = {}
				let tmpList = []
				obj.name = ruleForm.name
				obj.isAdmin = 2
				obj.status = 1
				obj.remark = ruleForm.remark
				newArrFn(ruleForm.limits)
				obj.roleMenuDtoList = ruleForm.limits
				try {
					if (title.value == "新建权限角色") {
						await postAxios("/system/sysRole/saveToAuth", obj)
						ElMessage.success("新建成功")
					} else {
						obj.id = editId.value
						await postAxios("/system/sysRole/editToAuth", obj)
						ElMessage.success("编辑成功")
					}
					del()
					visible.value = false
					created()
					window.triggerReload()
				} catch (error) {
					ElMessage.error(error)
					fabu.value = false
				}
			} else {
				console.log("error submit!", fields)
				fabu.value = false
			}
		})
	}
}
function newArrFn(arr) {
	let newArr = []
	for (let i = 0; i < arr.length; i++) {
		newArr.includes(arr[i]) ? newArr : newArr.push(arr[i])
	}
	return newArr
}

const authority = async row => {
	fabu.value = false
	try {
		authorityStr.value = row.id
		data.value = await getAxios("/system/sysDept/list")
		const { checkedData } = await getAxios(`/system/sysRole/dataAuthInfo?roleId=${row.id}`)
		defaultTree.value = []
		checkedData.forEach(item => {
			defaultTree.value.push(item.id)
		})
		authorityVis.value = true
		nextTick(() => {
			tree.value?.setCheckedKeys(defaultTree.value)
		})
	} catch (error) {
		ElMessage.error(error)
	}
}
const closes = () => {
	defaultTree.value = []
	authorityList.value = []
	authorityVis.value = false
}
const tableData = ref([])
async function created() {
	const res = await getAxios(`/system/sysRole/page?current=${current.value}&size=${pageSize.value}`)
	total.value = +res.total
	tableData.value = res.records
}
created()
//已选择用户

const selectClick = row => {
	selectList.value = row
}
const selectAll = row => {
	selectList.value = row
}
const delTableList = async val => {
	if (!val) {
		if (selectList.value.length == 0) {
			return ElMessage.error("请先选择用户")
		}
	}
	ElMessageBox.confirm("是否确认删除", "提示", {
		confirmButtonText: "确定",
		cancelButtonText: "取消",
		type: "warning",
	}).then(async () => {
		let tableList = []
		if (!val) {
			selectList.value.forEach(item => {
				tableList.push(item.id)
			})
		} else {
			tableList.push(val.id)
		}
		try {
			const res = await postAxios("/system/sysRole/deleteBatch", tableList)
			if (res != "删除成功") {
				ElMessage.error(res)
				selectList.value = []
				created()
			} else {
				ElMessage.success("删除成功")
				selectList.value = []
				created()
			}
		} catch (error) {
			ElMessage.error(error)
		}
	})
}
const title = ref("")
const userInfo = ref("")
const times = ref("")
const editId = ref("")
//新增
const add = async () => {
	title.value = "新建权限角色"
	visible.value = true
	fabu.value = false
	const { allData } = await getAxios("/system/sysRole/menuAuthList")
	limitsList.value = allData
	//个人信息
	const { realName } = await getAxios("/system/sysUser/selectById")
	userInfo.value = realName
	times.value = nowDate(new Date(dataTime))
}
//编辑
const editTable = async row => {
	editId.value = row.id
	title.value = "修改权限角色"
	visible.value = true
	fabu.value = false
	const { allData } = await getAxios("/system/sysRole/menuAuthList")
	limitsList.value = allData
	const res = await getAxios(`/system/sysRole/menuAuthInfoToRole?id=${row.id}`)
	ruleForm.name = res.name
	ruleForm.remark = res.remark
	times.value = res.createTime
	userInfo.value = res.createUserName
	defaultTree.value = []
	res.mapMenu.checkedData.forEach(item => {
		defaultTree.value.push(item.id)
		treeList(item.id)
	})
	nextTick(() => {
		limitsTree.value?.setCheckedKeys(defaultTree.value)
	})
}
function treeList(val) {
	limitsList.value.forEach(item => {
		item.children.forEach(it => {
			it.children.forEach(i => {
				if (i.id == val) {
					ruleForm.limits.push(item.id, it.id, i.id)
				}
			})
		})
	})
}
function del() {
	ruleForm.name = ""
	ruleForm.remark = ""
	ruleForm.limits = []
	selectList.value = []
	limitsList.value = []
	checkbox.value = []
	// isIndeterminate.value = []
}
const quXiao = () => {
	visible.value = false
	del()
}
function nowDate(now) {
	let year = now.getFullYear() //年份
	let month = now.getMonth() + 1 //月份（0-11）
	month = month < 10 ? "0" + month : month
	let date = now.getDate() //天数（1到31）
	date = date < 10 ? "0" + date : date
	let hour = now.getHours() //小时数（0到23）
	hour = hour < 10 ? "0" + hour : hour
	let minute = now.getMinutes() //分钟数（0到59）
	minute = minute < 10 ? "0" + minute : minute
	let second = now.getSeconds() //秒数（0到59）
	second = second < 10 ? "0" + second : second
	return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second
}

const checkChange = (checkedNodes, halfCheckedNodes) => {
	authorityList.value = []
	halfCheckedNodes.checkedNodes.forEach(item => {
		authorityList.value.push({
			deptId: item.id,
			roleId: authorityStr.value,
		})
	})
}
const onYes = async () => {
	if (fabu.value) {
		return
	} else {
		fabu.value = true
		try {
			await postAxios(`/system/sysRole/dataAuthSave/${authorityStr.value}`, authorityList.value)
			defaultTree.value = []
			authorityList.value = []
			authorityVis.value = false
			ElMessage.success("操作成功")
		} catch (error) {
			ElMessage.error(error)
			fabu.value = false
		}
	}
}
const handleCheckChange = (checkedNodes, halfCheckedNodes) => {
	ruleForm.limits = halfCheckedNodes.checkedKeys.concat(halfCheckedNodes.halfCheckedKeys)
}
</script>
<style lang="scss" scoped>
@import "/style/basis";
.title {
	font-size: 18px;
	margin-bottom: 15px;
}

.quanXian {
	background-color: #f8f8f8;
	height: 100%;

	:deep(.el-checkbox-group) {
		padding-left: 15px;
	}

	:deep(.el-collapse) {
		border: 1px solid #dcdfe6;
		border-radius: 5px;
	}

	:deep(.el-collapse-item__content) {
		padding: 10px;
	}

	:deep(.el-collapse-item__header) {
		height: 50px;
		background: #f5f7fa;
		padding: 0 0 0 10px;
	}

	.right {
		width: 250px;
		height: 100%;
		overflow-y: scroll;
		border-right: 1px solid #ebeef5;
		@include maxWidth(1024) {
			width: 200px;
		}
		@include maxWidth(900) {
			width: 170px;
		}
		@include maxWidth(768) {
			display: none;
		}

		.title .ctheme {
			width: 250px;
			height: 35px;
			line-height: 35px;
			background: #f0f5ff;
			padding: 0 30px;
			margin-top: 10px;
		}
	}

	:deep(.el-radio__input.is-checked .el-radio__inner::after) {
		background: #fff;
	}

	:deep(.cheng-dialog) {
		// width: 700px !important;
	}

	:deep(.cheng-dialog .bu-select) {
		width: 100% !important;
	}

	:deep(.bu-select .el-input__wrapper) {
		border-radius: 5px 0 0 5px !important;
	}

	:deep(.cheng-dialog .el-dialog__body) {
		padding: 20px 30px !important;
	}

	:deep(.cheng-dialog .el-select__tags .el-tag--info) {
		background: #f4faff;
		border: 1px solid #2972fa;
		border-radius: 20px;
		color: #2972fa;
	}

	.left-bottom {
		padding: 25px;

		.table-head2 {
			border: 1px solid #eceef5;
			height: 50px;
			padding: 0 2%;
		}

		.table-head {
			margin-bottom: 25px;

			:deep(.el-input) {
				border-radius: 3px;
				margin-right: 10pxm;
			}

			.primary {
				width: 90px;
				height: 30px;
				border-radius: 2px;
			}

			.danger {
				width: 90px;
				height: 30px;
				border-radius: 2px;
				margin-left: 20px;
			}
		}

		:deep(.el-table) {
			border: 1px solid #eceef5;
		}

		:deep(.el-table th.el-table__cell) {
			background-color: #f4f7fa;
		}

		:deep(.el-table .el-table__cell) {
			height: 50px;
			color: #606266;
		}
	}

	.left {
		margin: 25px;
		// height: 100%;
		overflow-y: scroll;
	}
}
.dialog-contents {
	// padding: 35px;
	overflow-y: scroll;
	height: 400px;
}
.labelTag {
	display: none;
	@include maxWidth(768) {
		display: flex;
		justify-content: flex-end;
	}
}
:deep(.dialog) {
	width: 700px !important;
}
:deep(.el-button) {
	&:focus {
		color: #606266;
		background-color: #fff;
		border: 1px solid #dcdfe6;
	}
}
.checkbox-item {
	padding: 10px;
}
.el-tree {
	max-height: 300px;
	overflow-y: scroll;
	width: 100%;
	// ::v-deep .el-tree-node__children {
	// 	width: 100%;
	// 	display: flex;
	// 	flex-direction: column;
	// 	.el-tree-node__children {
	// 		width: 100%;
	// 		display: flex;
	// 		flex-direction: row;
	// 		flex-wrap: wrap;
	// 		.el-tree-node__children {
	// 			width: 100%;
	// 			display: flex;
	// 			flex-direction: row;
	// 			flex-wrap: wrap;
	// 		}
	// 	}
	// }
}
</style>
